
const fs = require('fs');
const { DEFAULT_CONFIG_DIR } = require('../constant');
const axios = require('axios');
const shelljs = require('shelljs');
const Crypto = require('../utils/crypto');
const RcParser = require("./rc-parser");
const path = require('path');

async function getTokenLoginCookie(loginUrl, { ignoreCache, loginUser } = { loginUser: "8EBENJ2" }) {
  try {
    if (!ignoreCache) {
      const cachedCookie = getCachedCookie();
      if (cachedCookie) {
        return cachedCookie;
      }
    }
    clearCachedCookie();
    const authorization = {
      timestamp: new Date().getTime(),
      user: loginUser,
      nonce: Math.floor(Math.random() * 1000000),
      version: 'v1',
      pk: Crypto.getKey('public', loginUser).toString('utf8'),
    };
    // 因为json序列化和反序列化不能保证字段的顺序，所以不采用JSON.stringify(authorization)作为签名数据
    const originSignMsg = authorization.timestamp + authorization.user + authorization.nonce
      + authorization.version + authorization.pk;
    const authParam = {
      authorization,
      signature: Crypto.sign(originSignMsg, loginUser),
    };
    const res = await axios.get(`${loginUrl}?authorization_code=${encodeURIComponent(JSON.stringify(authParam))}`);
    if (res && res.headers['set-cookie']) {
      const cookie = (res.headers['set-cookie'] || []).join(';');
      if (cookie) {
        console.log("login success");
        setCachedCookie(cookie, loginUser);
        return cookie;
      }
    }
    throw res;
  } catch (err) {
    console.log(err);
  }
}

function getCachedCookie() {
  const cookieFile = path.resolve(DEFAULT_CONFIG_DIR, "user")
  if (fs.existsSync(cookieFile)) {
    const parser = RcParser.fromPath(cookieFile)
    return parser.get("cookie");
  }
  return '';
}

function setCachedCookie(cookie, loginUser) {
  const cookieFile = path.resolve(DEFAULT_CONFIG_DIR, "user")
  const json = {
    user: loginUser,
    cookie,
  };
  RcParser.saveJsonToFile(json, cookieFile)
}

function clearCachedCookie() {
  const cookieFile = path.resolve(DEFAULT_CONFIG_DIR, "user")
  shelljs.rm('-rf', cookieFile)
}

function getCsrfToken(cookie) {
  if (cookie) {
    const cookieList = cookie.split(';').map((c) => c.trim());
    const csrfTokenMark = 'hpmCsrfToken=';
    const csrfToken = cookieList.find((c) => c.startsWith(csrfTokenMark));
    if (csrfToken) {
      return csrfToken.substr(csrfTokenMark.length);
    }
  }
  return '';
}

module.exports = {
  getCachedCookie,
  getCsrfToken,
  getTokenLoginCookie,
  setCachedCookie,
  clearCachedCookie
};
